package m.member.order.service;

import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.member.order.model.OrderDetail;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;

public class OrderDetailService extends Service {

    public String save(OrderDetail model) throws Exception {
        ModelCheckUtil.checkNotNull(model,"order.oid","serve.oid","num");
        model.setServe(ModelQueryList.getModel(model.getServe(),"*"));
        model.setPrice(model.getServe().getPrice());
        model.setDiscount(model.getServe().getDiscount());
        model.setTotal(NumberUtil.round(model.getPrice()*model.getNum()*(100-model.getDiscount())/100.0,2));
        String msg;
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            if (ObjectUtil.isEmptyOid(model)) {
                model.setOid(GenerateID.generatePrimaryKey());
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                ModelUpdateUtil.updateModel(model,"order.oid","serve.oid","price","discount","total","num");
                msg="修改成功";
            }
            //更新订单金额
            getService(OrderInfoService.class).updateOrderAmount(model.getOrder().getOid());
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }
    public void delete(OrderDetail model) throws Exception {
        OrderDetail detail=ModelQueryList.getModel(model,"oid","order.oid","order.status");
        if(null!=detail&&"A".equals(detail.getOrder().getStatus())){
            TransactionManager tm=new TransactionManager();
            try{
                tm.begin();
                ModelUpdateUtil.deleteModel(detail);
                //更新订单金额
                getService(OrderInfoService.class).updateOrderAmount(detail.getOrder().getOid());
                tm.commit();
            }catch (Exception e){
                tm.rollback();
                throw e;
            }
        }else{
            throw new MException(this.getClass(),"只有未提交的订单才能删除");
        }
    }
}
